<?php

namespace app\api\Service;

use think\Db;
use think\Config;
use app\common\library\Auth;
use addons\epay\library\Service;
use fast\Http;

class OrderService
{
    // 获取下单路费
    public static function getTravelExpenses($data)
    {
        if(!$data['student_id']) return ['code'=>0, 'msg'=>'无效参数','data'=>''];
        $auth = Auth::instance();
        $user_id = $auth->id;

        $studentInfo = \app\admin\model\Student::where(['user_id'=>$user_id,'id'=>$data['student_id']])->field('school_lng,school_lat,home_lng,home_lat')->find();
        if(!$studentInfo) return ['code'=>0,'msg'=>'学生档案不存在','data'=>''];
        $from = [$studentInfo['school_lng'],$studentInfo['school_lat']];
        $to = [$studentInfo['home_lng'],$studentInfo['home_lat']];
        $distance = getDistanceBy2Point($from,$to);
        $mileage_fee = Config::get('site.mileage_fee');
        $travel_expenses = round(bcmul($distance, $mileage_fee, 3),2);
        return ['code'=>1,'msg'=>'获取成功','data'=>$travel_expenses];
    }

    // 获取可用优惠卷列表
    public static function getCouponLists($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $status = isset($data['status']) ? $data['status'] : 1;
        $service_fee = isset($data['service_fee']) ? $data['service_fee'] : 0;
        $where = ['user_id'=>$user_id,'status'=>$status,'reduction_amount'=>['<=',$service_fee]];

        $list = \app\admin\model\CouponUser::where($where)->field('id,name,reduction_amount,discount_amount,expiretime')->paginate($limit)
            ->each(
                function($item){
                    $item->expiretime_text = date('Y-m-d H:i:s', $item['expiretime']);
                    unset($item['expiretime']);
                    return $item;
                }
            );

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 查看委托书
    public static function LookContract($data){
        $auth = Auth::instance();
        $user_id = $auth->id;
        if(!$data['realname']) return ['code'=>0,'msg'=>'请填写姓名','data'=>''];
        if(!$data['id_number']) return ['code'=>0,'msg'=>'请填写身份证号','data'=>''];
        if(!$data['mobile']) return ['code'=>0,'msg'=>'请填写联系电话','data'=>''];
        if(!$data['address']) return ['code'=>0,'msg'=>'请填写家庭住址','data'=>''];
        if(!$data['start_school_one']) return ['code'=>0,'msg'=>'请填写上学开始时间','data'=>''];
        if(!$data['start_school_two']) return ['code'=>0,'msg'=>'请填写上学结束时间','data'=>''];
        if(!$data['over_school_one']) return ['code'=>0,'msg'=>'请填写放学开始时间','data'=>''];
        if(!$data['over_school_two']) return ['code'=>0,'msg'=>'请填写放学结束时间','data'=>''];
        if(!$data['parent_card']) return ['code'=>0,'msg'=>'请填上传家长卡','data'=>''];
        $student= \app\admin\model\Student::where(['id'=>$data['student_id'],'user_id'=>$user_id])->field('name,gender,school,grade')->find();
        if(!$student) return ['code'=>0,'msg'=>'学生档案不存在','data'=>''];

        $font_path = ROOT_PATH . '/public/assets/fonts/FangZhengFangSongJianTi-1.ttf';
        $bg_path = ROOT_PATH . '/public/entrust/template/template1.png';
        $yz_path = ROOT_PATH . '/public/entrust/template/stamp.png';
        $jz_path = ROOT_PATH . 'public'.$data['parent_card'];

        // A4 纸的像素高度和宽度（假设分辨率为 300 DPI）
        $a4_height = 2480;
        $a4_width = 1754;

        // 获取背景图和家长卡图片的尺寸
        list($bg_width, $bg_height) = getimagesize($bg_path);
        list($yz_width, $yz_height) = getimagesize($yz_path);
        list($jz_width, $jz_height) = getimagesize($jz_path);

        // 计算背景图的新高度（A4 纸高度的 3/4）
        $new_bg_height = (int) ($a4_height * 0.75);

        // 计算背景图的新宽度
        $new_bg_width = (int) ($bg_width * ($new_bg_height / $bg_height));

        // 计算背景图在画布中的起始 x 坐标（居中对齐）
        $bg_x = (int) (($a4_width - $new_bg_width) / 2);

        // 计算家长卡图片的新宽度（背景图宽度的 3/4）
        $new_jz_width = (int) ($new_bg_width * 0.75);

        // 计算家长卡图片的新高度
        $new_jz_height = (int) ($jz_height * ($new_jz_width / $jz_width));

        // 创建目标画布，高度为 A4 纸的像素高度，宽度为 A4 纸的宽度
        $canvas = imagecreatetruecolor($a4_width, $a4_height);
        $white = imagecolorallocate($canvas, 255, 255, 255); // 设置白色背景
        imagefill($canvas, 0, 0, $white);

        // 加载背景图和家长卡图片
        $backgroupImg = imagecreatefromstring(file_get_contents($bg_path));
        $stampImg = imagecreatefromstring(file_get_contents($yz_path));
        $jzcardImg = imagecreatefromstring(file_get_contents($jz_path));

        // 将背景图调整到新的宽度和高度，并居中复制到目标画布的顶部
        imagecopyresampled($canvas, $backgroupImg, $bg_x, 0, 0, 0, $new_bg_width, $new_bg_height, $bg_width, $bg_height);

        // 计算家长卡图片在画布中的起始 y 坐标
        $jz_y = $new_bg_height;

        // 将家长卡图片调整到新的宽度和高度，并复制到目标画布的底部，左边对齐
        imagecopyresampled($canvas, $jzcardImg, $bg_x, $jz_y, 0, 0, $new_jz_width, $new_jz_height, $jz_width, $jz_height);

        // 将印章放入画布中
        imagecopyresampled($canvas, $stampImg, 1050, 1670, 0, 0, $yz_width, $yz_height, $yz_width, $yz_height);

        // 保存图片
        $new_file = "entrust/image/" . date('Ymd', time()) . "/";
        if (!file_exists($new_file)) {
            // 检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700, true);
        }
        $template = $new_file . $user_id . ".png";

        imagepng($canvas, $template);

        // 释放内存
        imagedestroy($canvas);
        imagedestroy($backgroupImg);
        imagedestroy($jzcardImg);

        $realname = $data['realname'];$id_number = $data['id_number'];$mobile = $data['mobile'];$address = $data['address'];$student_age = $data['student_age'];
        $start_school_one = $data['start_school_one'];$start_school_two = $data['start_school_two'];$over_school_one = $data['over_school_one'];$over_school_two = $data['over_school_two'];
        $student_name= $student['name'];$student_gender = $student['gender'] ? '女' : '男';$student_school = $student['school'];$student_grade = $student['grade'];

        $image_path = 'entrust/bg/'.date('Ymd',time()).'/';
        if(!file_exists($image_path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($image_path, 0700);
        }
        $image_path = $image_path.$user_id.'.png';
        $echo_path = ROOT_PATH . '/public/'.$image_path;

        strlen($address) > 20 ? $font_size = 18 : $font_size = 18;

        $realname_path = self::imageAddText($template,$realname,520,115,  $font_path,18, $echo_path);
        $id_number_path = self::imageAddText($realname_path,$id_number,900,115,  $font_path,18, $echo_path);
        $mobile_path = self::imageAddText($id_number_path,$mobile,550,150,  $font_path,18, $echo_path);
        $address_path = self::imageAddText($mobile_path,$address,820,150,  $font_path,$font_size, $echo_path);
        $student_name_path = self::imageAddText($address_path,$student_name,550,470,  $font_path,18, $echo_path);
        $student_gender_path = self::imageAddText($student_name_path,$student_gender,1040,470,  $font_path,18, $echo_path);
        $student_age_path = self::imageAddText($student_name_path,$student_age,1250,470,  $font_path,18, $echo_path);
        $student_school_path = self::imageAddText($student_age_path,$student_school,500,500,  $font_path,18, $echo_path);
        $student_grade_path = self::imageAddText($student_school_path,$student_grade,1040,500,  $font_path,18, $echo_path);
        $start_school_one_path = self::imageAddText($student_grade_path,$start_school_one,780,785,  $font_path,18, $echo_path);
        $start_school_two_path = self::imageAddText($start_school_one_path,$start_school_two,950,785,  $font_path, 18, $echo_path);
        $over_school_one_path = self::imageAddText($start_school_two_path,$over_school_one,1180,785,  $font_path,18, $echo_path);
        $over_school_two_path = self::imageAddText($over_school_one_path,$over_school_two,500,825,  $font_path,18, $echo_path);
        $year_path = self::imageAddText($over_school_two_path,date('Y'),1000,1495,  $font_path,18, $echo_path);
        $month_path = self::imageAddText($year_path,date('m'),1130,1495,  $font_path,18, $echo_path);
        $day_path = self::imageAddText($month_path,date('d'),1220,1495,  $font_path,18, $echo_path);

        return ['code'=>1,'msg'=>'操作成功','data'=>['img'=>request()->domain().'/'.$image_path,'void'=>request()->domain().'/'.$template]];
    }

    public static function LookContracts($data){
        $auth = Auth::instance();
        $user_id = $auth->id;
        if(!$data['realname']) return ['code'=>0,'msg'=>'请填写姓名','data'=>''];
        if(!$data['id_number']) return ['code'=>0,'msg'=>'请填写身份证号','data'=>''];
        if(!$data['mobile']) return ['code'=>0,'msg'=>'请填写联系电话','data'=>''];
        if(!$data['address']) return ['code'=>0,'msg'=>'请填写家庭住址','data'=>''];
        if(!$data['start_school_one']) return ['code'=>0,'msg'=>'请填写上学开始时间','data'=>''];
        if(!$data['start_school_two']) return ['code'=>0,'msg'=>'请填写上学结束时间','data'=>''];
        if(!$data['over_school_one']) return ['code'=>0,'msg'=>'请填写放学开始时间','data'=>''];
        if(!$data['over_school_two']) return ['code'=>0,'msg'=>'请填写放学结束时间','data'=>''];
        if(!$data['parent_card']) return ['code'=>0,'msg'=>'请填上传家长卡','data'=>''];
        $student= \app\admin\model\Student::where(['id'=>$data['student_id'],'user_id'=>$user_id])->field('name,gender,school,grade')->find();
        if(!$student) return ['code'=>0,'msg'=>'学生档案不存在','data'=>''];

        $font_path = ROOT_PATH . '/public/assets/fonts/FangZhengFangSongJianTi-1.ttf';
        $bg_path = ROOT_PATH . '/public/entrust/template/template1.png';
        $yz_path = ROOT_PATH . '/public/entrust/template/stamp.png';
        $jz_path = ROOT_PATH . 'public'.$data['parent_card'];

        // A4 纸的像素高度和宽度（假设分辨率为 300 DPI）
        $a4_height = 2480;
        $a4_width = 1754;

        // 获取背景图和家长卡图片的尺寸
        list($bg_width, $bg_height) = getimagesize($bg_path);
        list($yz_width, $yz_height) = getimagesize($yz_path);
        list($jz_width, $jz_height) = getimagesize($jz_path);

        // 计算背景图的新高度（A4 纸高度的 3/4）
        $new_bg_height = (int) ($a4_height * 0.75);

        // 计算背景图的新宽度
        $new_bg_width = (int) ($bg_width * ($new_bg_height / $bg_height));

        // 计算背景图在画布中的起始 x 坐标（居中对齐）
        $bg_x = (int) (($a4_width - $new_bg_width) / 2);

        // 计算家长卡图片的新宽度（背景图宽度的 3/4）
        $new_jz_width = (int) ($new_bg_width * 0.75);

        // 计算家长卡图片的新高度
        $new_jz_height = (int) ($jz_height * ($new_jz_width / $jz_width));

        // 创建目标画布，高度为 A4 纸的像素高度，宽度为 A4 纸的宽度
        $canvas = imagecreatetruecolor($a4_width, $a4_height);
        $white = imagecolorallocate($canvas, 255, 255, 255); // 设置白色背景
        imagefill($canvas, 0, 0, $white);

        // 加载背景图和家长卡图片
        $backgroupImg = imagecreatefromstring(file_get_contents($bg_path));
        $stampImg = imagecreatefromstring(file_get_contents($yz_path));
        $jzcardImg = imagecreatefromstring(file_get_contents($jz_path));

        // 将背景图调整到新的宽度和高度，并居中复制到目标画布的顶部
        imagecopyresampled($canvas, $backgroupImg, $bg_x, 0, 0, 0, $new_bg_width, $new_bg_height, $bg_width, $bg_height);

        // 计算家长卡图片在画布中的起始 y 坐标
        $jz_y = $new_bg_height;

        // 将家长卡图片调整到新的宽度和高度，并复制到目标画布的底部，左边对齐
        imagecopyresampled($canvas, $jzcardImg, $bg_x, $jz_y, 0, 0, $new_jz_width, $new_jz_height, $jz_width, $jz_height);

        // 将印章放入画布中
        imagecopyresampled($canvas, $stampImg, 1050, 1670, 0, 0, $yz_width, $yz_height, $yz_width, $yz_height);

        // 保存图片
        $new_file = "entrust/image/" . date('Ymd', time()) . "/";
        if (!file_exists($new_file)) {
            // 检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700, true);
        }
        $template = $new_file . $user_id . ".png";

        imagepng($canvas, $template);

        // 释放内存
        imagedestroy($canvas);
        imagedestroy($backgroupImg);
        imagedestroy($jzcardImg);

        $realname = $data['realname'];$id_number = $data['id_number'];$mobile = $data['mobile'];$address = $data['address'];$student_age = $data['student_age'];
        $start_school_one = $data['start_school_one'];$start_school_two = $data['start_school_two'];$over_school_one = $data['over_school_one'];$over_school_two = $data['over_school_two'];
        $student_name= $student['name'];$student_gender = $student['gender'] ? '女' : '男';$student_school = $student['school'];$student_grade = $student['grade'];

        $image_path = 'entrust/bg/'.date('Ymd',time()).'/';
        if(!file_exists($image_path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($image_path, 0700);
        }
        $image_path = $image_path.$user_id.'.png';
        $echo_path = ROOT_PATH . '/public/'.$image_path;

        strlen($address) > 20 ? $font_size = 18 : $font_size = 18;

        $realname_path = self::imageAddText($template,$realname,520,115,  $font_path,18, $echo_path);
        $id_number_path = self::imageAddText($realname_path,$id_number,900,115,  $font_path,18, $echo_path);
        $mobile_path = self::imageAddText($id_number_path,$mobile,550,150,  $font_path,18, $echo_path);
        $address_path = self::imageAddText($mobile_path,$address,820,150,  $font_path,$font_size, $echo_path);
        $student_name_path = self::imageAddText($address_path,$student_name,550,470,  $font_path,18, $echo_path);
        $student_gender_path = self::imageAddText($student_name_path,$student_gender,1040,470,  $font_path,18, $echo_path);
        $student_age_path = self::imageAddText($student_name_path,$student_age,1250,470,  $font_path,18, $echo_path);
        $student_school_path = self::imageAddText($student_age_path,$student_school,500,500,  $font_path,18, $echo_path);
        $student_grade_path = self::imageAddText($student_school_path,$student_grade,1040,500,  $font_path,18, $echo_path);
        $start_school_one_path = self::imageAddText($student_grade_path,$start_school_one,780,785,  $font_path,18, $echo_path);
        $start_school_two_path = self::imageAddText($start_school_one_path,$start_school_two,950,785,  $font_path, 18, $echo_path);
        $over_school_one_path = self::imageAddText($start_school_two_path,$over_school_one,1180,785,  $font_path,18, $echo_path);
        $over_school_two_path = self::imageAddText($over_school_one_path,$over_school_two,500,825,  $font_path,18, $echo_path);
        $year_path = self::imageAddText($over_school_two_path,date('Y'),1000,1495,  $font_path,18, $echo_path);
        $month_path = self::imageAddText($year_path,date('m'),1130,1495,  $font_path,18, $echo_path);
        $day_path = self::imageAddText($month_path,date('d'),1220,1495,  $font_path,18, $echo_path);

        return ['code'=>1,'msg'=>'操作成功','data'=>['img'=>request()->domain().'/'.$image_path,'void'=>request()->domain().'/'.$template]];
    }

    // 签署委托书
    public static function SignContract($data){
        // ini_set('memory_limit', '256M');

        $auth = Auth::instance();
        $user_id = $auth->id;

        $signImg = ROOT_PATH . '/public' . self::base64_image_content($data['user_sign'],'entrust');
        // 旋转270度
        self::rotateImageGD($signImg, $signImg);

        $bgImg = ROOT_PATH . "/public/entrust/bg/".date('Ymd',time())."/{$user_id}.png";

        $backgroupImg = imagecreatefromstring(file_get_contents($bgImg));
        $usersignImg = imagecreatefromstring(file_get_contents($signImg));
        // return 123;
        //获取新的尺寸
        list($width, $height) = getimagesize($signImg);
        $new_width = $width * 2;
        $new_height = $height * 2;
        //重新组合图片并调整大小
        imagecopyresampled($backgroupImg,$usersignImg,1000, 1630, 0, 0,$new_width, $new_height, $width, $height);//输出图片

        $new_file = "entrust/sign/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.$user_id.".png";
        // 保存图片
        imagepng($backgroupImg, $new_file);

        // 释放内存
        imagedestroy($backgroupImg);

        // 写入年月日
        $font_path = ROOT_PATH . '/public/assets/fonts/FangZhengFangSongJianTi-1.ttf';
        $bg_path = $new_file;
        $echo_path = "entrust/sign/".date('Ymd',time())."/".date('YmdHis',time()).'_'.$user_id.".png";

        $year_path = self::imageAddText($bg_path,date('Y'),1050,1850,  $font_path,20, $echo_path);
        $month_path = self::imageAddText($year_path,date('m'),1150,1850,  $font_path,20, $echo_path);
        $day_path = self::imageAddText($month_path,date('d'),1210,1850,  $font_path,20, $echo_path);

        return ['code'=>1,'msg'=>'操作成功','data'=>['img'=>request()->domain().'/'.$day_path]];
    }

    // 新增
    public static function add($data)
    {
        try{
            $auth = Auth::instance();
            $data['user_id'] = $auth->id;
            $data['coupon_id'] = isset($data['coupon_id']) ? $data['coupon_id'] : 0;
            $data['is_transfer'] = isset($data['is_transfer']) && $data['is_transfer']? $data['is_transfer'] : 0;
            $data['is_life'] = isset($data['is_life']) && $data['is_life'] ? $data['is_life'] : 0;
            $data['custom_service'] = isset($data['custom_service']) && $data['custom_service'] ? $data['custom_service'] : '';

//            $data['gender'] = isset($data['gender']) ? $data['gender'] : 0;
            if(!$data['student_id']) return ['code'=>0, 'msg'=>'学生档案错误','data'=>''];
            if(!$data['service_id']) return ['code'=>0, 'msg'=>'服务套餐错误','data'=>''];
            if($data['is_transfer'] && !$data['contract']) return ['code'=>0, 'msg'=>'无效的委托书','data'=>''];
//            if(!$data['custom_service']) return ['code'=>0, 'msg'=>'请填选择定制服务','data'=>''];
            if(!$data['reservedtime']) return ['code'=>0, 'msg'=>'请填选择预约时间','data'=>''];
//            if(!$data['reservedforte']) return ['code'=>0, 'msg'=>'请填选择管家特长','data'=>''];
            $data['service_type'] = \app\admin\model\ServicePackage::where(['id'=>$data['service_id']])->value('type');

            if(isset($data['custom_service']) && $data['custom_service']){
                $custom_service = explode(",", $data['custom_service']);
                if(count($custom_service) > 3) return ['code'=>0, 'msg'=>'定制服务一单最多选择3个','data'=>''];
            }

            // 服务费
            if($data['custom_service']){
                $data['service_fee'] = \app\admin\model\Service::where(['id'=>['in',$data['custom_service']],'status'=>'normal'])->sum('price');
                $data['service_duration'] = \app\admin\model\Service::where(['id'=>['in',$data['custom_service']],'status'=>'normal'])->sum('duration');
            }else{
                $data['service_fee'] = 0;
                $data['service_duration'] = 0;
            }
            if($data['is_transfer']) {
                $transfer_fee = Config::get('site.transfer_service_price');
                $data['service_fee'] += $transfer_fee;
                $data['service_duration'] += 1;
            }
            if($data['is_life']) {
                $life_fee = Config::get('site.life_service_price');
                $data['service_fee'] += $life_fee;
                $data['service_duration'] += 1;
            }

            // 路费
//            $ret = self::getTravelExpenses($data);
            $data['travel_expenses'] = 0;
            // 总金额
            $total_price = $data['total_price'] = round(bcadd($data['service_fee'], $data['travel_expenses'], 3),2);

            // 优惠卷处理
            $data['coupon_price'] = 0;
            if($data['coupon_id']) {
                // 优惠劵信息
                $couponInfo = \app\admin\model\CouponUser::where(['user_id'=>$data['user_id'],'id'=>$data['coupon_id']])->field('status,reduction_amount,discount_amount')->find();
                // 判断优惠劵是否存在
                if(!$couponInfo) return ['code'=>0, 'msg'=>'优惠卷不存在','data'=>''];
                // 优惠劵未使用
                $status = $couponInfo['status'];
                if($status == 1) {
                    // 判断是否满足使用条件
                    if($total_price >= $couponInfo['reduction_amount']) {
                        // 优惠金额
                        $data['coupon_price'] = $couponInfo['discount_amount'];
                    }else{
                        return ['code'=>0, 'msg'=>"订单总金额不足{$couponInfo['reduction_amount']}元",'data'=>''];
                    }
                }
                // 优惠劵已使用
                if($status == 2) return ['code'=>0, 'msg'=>'优惠卷已使用','data'=>''];
                // 优惠卷已失效
                if($status == 3) return ['code'=>0, 'msg'=>'优惠卷已失效','data'=>''];
            }

            // 学生档案
            $studentInfo = \app\admin\model\Student::where(['id'=>$data['student_id']])->field('name,school_region,school_addr,home_region,home_addr')->find();
            if(!$studentInfo) return ['code'=>0,'msg'=>'学生档案不存在','data'=>''];
            $data['student_name'] = $studentInfo['name'];
            $data['school_addr'] = $studentInfo['school_region'] . $studentInfo['school_addr'];
            $data['home_addr'] = $studentInfo['home_region'] . $studentInfo['home_addr'];

            // 下单数据
            $data['order_no'] = 'S'.getNewOrderNo();
            $params = [
                'user_id' => $data['user_id'],
                'order_no' => $data['order_no'],
                'student_id' => $data['student_id'],
                'coupon_price' => $data['coupon_price'],
                'student_name' => $data['student_name'],
                'school_addr' => $data['school_addr'],
                'home_addr' => $data['home_addr'],
                'service_id' => $data['service_id'],
                'service_type' => $data['service_type'],
                'is_transfer' => $data['is_transfer'],
                'custom_service' => $data['custom_service'],
                'is_transfer' => $data['is_transfer'],
                'is_life' => $data['is_life'],
                'service_fee' => $data['service_fee'],
                'service_duration' => $data['service_duration'],
                'travel_expenses' => $data['travel_expenses'],
                'total_price' => $data['total_price'],
                'reservedforte' => $data['reservedforte'],
                'contract' => $data['contract'],
                'reservedtime' => strtotime($data['reservedtime']),
//                'expiretime' => time() + 15*60,// 15分钟后过期
                'mark' => $data['mark']
            ];

            $result = \app\admin\model\Order::create($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){

            //修改优惠券状态
            if( $data['coupon_id'] ){
                $coupon_result = \app\admin\model\CouponUser::where(['user_id'=>$data['user_id'],'id'=>$data['coupon_id']])->update([
                        'status'=>2,
                        'usetime' => time()
                    ]);
            }

            return ['code'=>1,'msg'=>'操作成功','data'=>['id'=>$result['id']]];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 支付
    public static function pay($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        if( !$id ){
            return ['code'=>0,'msg'=>'请选择要操作的订单','data'=>''];
        }
        if( !$user_id ){
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }

        //判断订单是否存在
        $order = \app\admin\model\Order::where('id',$id)->where('user_id',$user_id)->find();

        if( !$order ){
            return ['code'=>0,'msg'=>'订单信息不存在','data'=>''];
        }
        if( $order['paid'] == 1 ){
            return ['code'=>0,'msg'=>'订单已支付','data'=>''];
        }

        if( !in_array($data['pay_type'],[1,2]) ) return ['code'=>0, 'msg'=>'请选择支付方式','data'=>''];
        $data['total_price'] = isset($data['total_price']) ? $data['total_price'] : 0;
        $data['pay_price'] = isset($data['pay_price']) ? $data['pay_price'] : 0;

        // 订单总金额
        $total_price = round(bcadd($order['service_fee'], $order['travel_expenses'], 3),2);
        if($total_price != $data['total_price']) return ['code'=>0, 'msg'=>'订单总金额错误','data'=>''];

        // 实际价格
        $pay_price = round(bcsub($total_price, $order['coupon_price'], 3),2);
        if($pay_price != $data['pay_price']) return ['code'=>0, 'msg'=>'实际支付金额错误','data'=>''];

        try{
            $params = [
                'pay_type'         => $data['pay_type'],
                'total_price'      => $data['total_price'],
                'pay_price'        => $data['pay_price'],
            ];

            $result = \app\admin\model\Order::where(['id'=>$id])->update($params);
//            $result = true;

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

        if($result){

            $pay_type = ['1'=>'wechat','2'=>'alipay'];
            $type = $pay_type[$data['pay_type']];
            $title = \app\admin\model\ServicePackage::where(['id'=>$order['service_id']])->value('title');
            $params = [
                'amount'    => $data['pay_price'],
                'orderid'   => $order['order_no'],
                'type'      => $type,
                'title'     => '【'.$title.'】',
                'method'    => 'app',
            ];
//            $params['amount'] = 0.01;// 测试支付
            $response = Service::submitOrder($params);

            if($data['pay_type'] == 1){
                $response = json_decode($response,true);
            }
            return ['code'=>1,'msg'=>'操作成功','data'=>$response];

            // 跳过支付
//            $ret = self::payResult(['out_trade_no' => $order['order_no'],'transaction_id' => $order['order_no']]);
//            return $ret;


        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 列表 state "-1":__('待付款'),"0":__('待接单'),"1":__('服务中'),"2":__('已完成'),"7":__('已取消')
    public static function lists($data)
    {
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $auth = Auth::instance();
        $user_id = $auth->id;
        $where['user_id'] = $user_id;
        $where['deletetime'] = null;

        if(strlen($data['state']) && $data['state'] == 0){
            $where['paid'] = 1;$where['status'] = 0;
        }
        if(isset($data['state']) && $data['state'] == 1){
            $where['paid'] = 1;$where['status'] = ['IN', '1,2,3,4'];
        }
        if(isset($data['state']) && $data['state'] == 2){
            $where['paid'] = 1;$where['status'] = 5;
        }
        if(isset($data['state']) && $data['state'] == 7){
            $where['status'] = ['IN', '100,101,102,103'];
        }
        if(isset($data['state']) && $data['state'] == -1){
            $where['paid'] = 0;$where['status'] = 0;
        }

        $list = \app\admin\model\Order::where($where)->order('createtime desc')->field('id,student_name,school_addr,home_addr,service_id,coupon_price,total_price,pay_price,paid,status')
            ->paginate($limit)->each(
                function($item){
                    $item['service_name'] = \app\admin\model\ServicePackage::where(['id'=>$item['service_id']])->value('title');

                    if($item['pay_price'] == 0) {
                        $item['pay_price'] = round(bcsub($item['total_price'], $item['coupon_price'], 3),2);
                    }

                    return $item;
                }
            );

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    //详情 state "-1":__('待付款'),"0":__('待接单'),"1":__('服务中'),"2":__('已完成'),"7":__('已取消')
    public static function detail($data)
    {
        $detail = \app\admin\model\Order::where(['id'=>$data['id']])->field('id,steward_id,student_name,student_photo,school_addr,home_addr,service_id,mark,reservedtime,reservedforte,service_fee,travel_expenses,coupon_id,coupon_price,total_price,pay_price,order_no,createtime,paidtime,receivetime,reachtime,dealtime,paid,status')
            ->find();

        if($detail){
            $stewardInfo = \app\admin\model\Steward::where(['id'=>$detail['steward_id']])->field('lng,lat,realname,avatar,age,forte,gender')->find();
            if($stewardInfo){
                $detail['steward_lng'] = $stewardInfo['lng'];
                $detail['steward_lat'] = $stewardInfo['lat'];
                $detail['steward_name'] = $stewardInfo['realname'];
                $detail['steward_avatar'] = $stewardInfo['avatar'];
                $detail['steward_age'] = $stewardInfo['age'];
                $detail['steward_gender'] = $stewardInfo['gender'];
                $detail['steward_forte'] = explode(',',$stewardInfo['forte']);
            }else{
                $detail['steward_lng'] = '';
                $detail['steward_lat'] = '';
                $detail['steward_name'] = '';
                $detail['steward_avatar'] = '';
                $detail['steward_age'] = '';
                $detail['steward_gender'] = '';
                $detail['steward_forte'] = '';
            }
            $service = \app\admin\model\ServicePackage::where(['id'=>$detail['service_id']])->field('title,image')
                ->find();
            if($service){
                $detail['service_title'] = $service['title'];
                $detail['service_image'] = $service['image'];
            }else{
                $detail['service_title'] = '服务';
            }
            if($detail['pay_price'] == 0){
                $detail['pay_price'] = round(bcsub($detail['total_price'], $detail['coupon_price'], 3),2);
            }


            $detail['reservedtime_text'] = date('Y-m-d H:i', $detail['reservedtime']);
            $coupon_name = \app\admin\model\Coupon::where(['id'=>$detail['coupon_id']])->value('name');
            if($coupon_name){
                $detail['coupon_name'] = $coupon_name;
            }else{
                $detail['coupon_name'] = '优惠劵';
            }
            $detail['createtime_text'] = date('Y-m-d H:i', $detail['createtime']);
            if($detail['paidtime']){
                $detail['paidtime_text'] = date('Y-m-d H:i', $detail['paidtime']);
            }else{
                $detail['paidtime_text'] = '';
            }
            if($detail['receivetime']){
                $detail['receivetime_text'] = date('Y-m-d H:i', $detail['receivetime']);
            }else{
                $detail['receivetime_text'] = '';
            }
            if($detail['reachtime']){
                $detail['reachtime_text'] = date('Y-m-d H:i', $detail['reachtime']);
            }else{
                $detail['reachtime_text'] = '';
            }
            if($detail['dealtime']){
                $detail['dealtime_text'] = date('Y-m-d H:i', $detail['dealtime']);
            }else{
                $detail['dealtime_text'] = '';
            }

            // 有没有加钟
            $extra = \app\admin\model\OrderExtra::where(['order_id'=>$data['id'],'paid'=>1])->field('id,title,duration,price')
                ->select();
            if($extra){
                $detail['extra'] = $extra;
            }else{
                $detail['extra'] = [];
            }

            unset($detail['service_id']);
            unset($detail['coupon_id']);
            unset($detail['createtime']);
            unset($detail['paidtime']);
            unset($detail['receivetime']);
            unset($detail['reachtime']);
            unset($detail['dealtime']);
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>$detail];
    }

    // 取消
    public static function cancel($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        if (!$id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }
        if (!$user_id) {
            return ['code' => 0, 'msg' => '用户信息不存在', 'data' => ''];
        }

        //判断订单是否存在
        $order = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->find();

        if (!$order) {
            return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
        }
        if ( in_array($order['status'],['100','101','102','103']) ) {
            return ['code' => 0, 'msg' => '订单已取消', 'data' => ''];
        }
        // 支付状态和订单状态
        try{
            if($order['pay_type'] == 1){
                $pay_type = 'wechat';
            }else{
                $pay_type = 'alipay';
            }
            $order['pay_price'] = '0.01';
            $paid = $order['paid'];$status = $order['status'];
            if( $paid == 0 && $status == 0 ) {
                $params = ['status'=>100,'updatetime'=>time(),'canceltime'=>time()];
                // 修改订单状态
                $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update($params);
                // 返还优惠劵
                if($order['coupon_id']){
                    $coupon = \app\admin\model\CouponUser::where('id', $order['coupon_id'])->where('user_id', $order['user_id'])->update(['status'=>1,'usetime'=>'']);
                }
            }elseif( $paid == 1 && $status == 0 ) {
                $params = ['status'=>100,'updatetime'=>time(),'canceltime'=>time()];
                // 修改订单状态
                $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update($params);
                // return $order['pay_price'];
                // 没有管家接单，退全款
                $response = Service::submitRefund($order['pay_price'],$order['pay_price'],$order['order_no'],$order['trade_no'], $pay_type, '用户取消订单', '', '', 'app');
                // 返还优惠劵
                if($order['coupon_id']){
                    $coupon = \app\admin\model\CouponUser::where('id', $order['coupon_id'])->where('user_id', $order['user_id'])->update(['status'=>1]);
                }
            }elseif( $paid == 1 && $status == 1 ) {
                $params = ['status'=>101,'updatetime'=>time(),'canceltime'=>time()];
                // 修改订单状态
                $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update($params);
                // 管家接单，不退路费，只退服务费
                $amount = round(bcsub($order['pay_price'], $order['travel_expenses'], 3),2);
                $amount = 0.01;// 测试退款
                if($amount<=0.01) $amount = 0.01;
                $response = Service::submitRefund($amount,$order['pay_price'],$order['order_no'],$order['trade_no'], $pay_type, '用户取消订单', '', '', 'app');
                // 返还优惠券
                if($order['coupon_id']){
                    $coupon = \app\admin\model\CouponUser::where('id', $order['coupon_id'])->where('user_id', $order['user_id'])->update(['status'=>1]);
                }
                // 管家收入 只有路费
                $memo = "用户取消订单：{$order->order_no}，收入路费";
                $ret = \app\admin\model\Steward::money($amount, $order->steward_id, $memo, $order->id);
                // 通知管家
                $steward_user_id = \app\admin\model\Steward::where(['id'=>$order->steward_id])->value('user_id');
                $mobile = \app\admin\model\User::where(['id'=>$user_id])->value('mobile');
                sendSmsNotice($mobile,4);
                // 修改管家状态
                \app\admin\model\Steward::where(['id'=>$order->steward_id])->update(['service_status'=>1, 'updatetime'=>time()]);
            }elseif( $paid == 1 && $status == 2 ) {
                $params = ['status'=>102,'updatetime'=>time(),'canceltime'=>time()];
                // 修改订单状态
                $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update($params);
                // 管家出发，只退订单金额40%
                $amount = round(bcmul($order['pay_price'], (40/100), 3),2);
                $amount = 0.01;// 测试退款
                if($amount<=0.01) $amount = 0.01;
                $response = Service::submitRefund($amount, $amount, $order['order_no'],$order['trade_no'], $pay_type, '用户取消订单', '', '', 'app');
                // 返还优惠劵
                if($order['coupon_id']){
                    $coupon = \app\admin\model\CouponUser::where('id', $order['coupon_id'])->where('user_id', $order['user_id'])->update(['status'=>1]);
                }
                // 管家收入 订单总金额的40%
                $memo = "用户取消订单：{$order->order_no}，收入订单金额40%";
                $ret = \app\admin\model\Steward::money($amount, $order->steward_id, $memo, $order->id);
                // 通知管家
                $steward_user_id = \app\admin\model\Steward::where(['id'=>$order->steward_id])->value('user_id');
                $mobile = \app\admin\model\User::where(['id'=>$user_id])->value('mobile');
                sendSmsNotice($mobile,4);
                // 修改管家状态
                \app\admin\model\Steward::where(['id'=>$order->steward_id])->update(['service_status'=>1, 'updatetime'=>time()]);
            }elseif( $paid == 1 && $status == 3 ) {
                $params = ['status'=>103,'updatetime'=>time(),'canceltime'=>time()];
                // 修改订单状态
                $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update($params);
                // 管家出发，只退订单金额40%
                $amount = round(bcmul($order['pay_price'], (40/100), 3),2);
                $amount = 0.01;// 测试退款
                if($amount<=0.01) $amount = 0.01;
                $response = Service::submitRefund($amount, $amount, $order['order_no'],$order['trade_no'], $pay_type, '用户取消订单', '', '', 'app');
                // 返还优惠劵
                if($order['coupon_id']){
                    $coupon = \app\admin\model\CouponUser::where('id', $order['coupon_id'])->where('user_id', $order['user_id'])->update(['status'=>1]);
                }
                // 管家收入 订单总金额的40%
                $memo = "用户取消订单：{$order->order_no}，收入订单金额40%";
                $ret = \app\admin\model\Steward::money($amount, $order->steward_id, $memo, $order->id);
                // 通知管家
                $steward_user_id = \app\admin\model\Steward::where(['id'=>$order->steward_id])->value('user_id');
                $mobile = \app\admin\model\User::where(['id'=>$user_id])->value('mobile');
                sendSmsNotice($mobile,4);
                // 修改管家状态
                \app\admin\model\Steward::where(['id'=>$order->steward_id])->update(['service_status'=>1, 'updatetime'=>time()]);
            }elseif( $paid == 1 && $status == 4) {
                return ['code'=>0,'msg'=>'管家正在服务中订单不可取消','data'=>''];
            }elseif( $paid == 1 && $status == 5) {
                return ['code'=>0,'msg'=>'管家服务已完成订单不可取消','data'=>''];
            }

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }


    }

    // 开始服务
    public static function serviceOrder($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        if (!$id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }
        if (!$user_id) {
            return ['code' => 0, 'msg' => '用户信息不存在', 'data' => ''];
        }

        //判断订单是否存在
        $order = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->find();

        if (!$order) {
            return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
        }
        if ( $order['status'] != 3 ) {
            return ['code' => 0, 'msg' => '订单状态异常', 'data' => ''];
        }

        try{
            $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update(['status'=>4,'updatetime'=>time()]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 确认
    public static function confirmOrder($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        if (!$id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }
        if (!$user_id) {
            return ['code' => 0, 'msg' => '用户信息不存在', 'data' => ''];
        }

        //判断订单是否存在
        $order = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->find();

        if (!$order) {
            return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
        }
        if ( $order['status'] != 4 ) {
            return ['code' => 0, 'msg' => '订单还未开始服务不可结束订单', 'data' => ''];
        }

        if ( ($order['custom_service'] || $order['is_life']) && $order['overtime'] > time()) {
            return ['code' => 0, 'msg' => '还未到服务结束时间', 'data' => ''];
        }

        try{

            $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update(['status'=>5,'updatetime'=>time(),'dealtime'=>time(),'settletime'=>time()]);
//            $result = true;
            if($result){
                $take_a_percentage = 1-(Config::get('site.take_a_percentage')/100);
                if(!$order->settletime){
                    // 保存订单收入
                    $amount = round(bcmul($order->pay_price, $take_a_percentage, 3),2);
//                    $memo = "订单：{$order->order_no}收入";
                    $memo = "订单收入";
                    $ret = \app\admin\model\Steward::money($amount, $order->steward_id, $memo, $order->id);
                }

                // 保存加钟收入
                $extra = \app\admin\model\OrderExtra::where(['order_id'=>$id,'paid'=>1,'settletime'=>null])->field('extra_id,price')->select();
                if($extra){
                    foreach ($extra as $v){
                        $amount = round(bcmul($v['price'], $take_a_percentage, 3),2);
                        $title = \app\admin\model\ServiceExtra::where(['id'=>$v['extra_id']])->value('title');
//                        $memo = "订单：{$order->order_no}加钟{$title}收入";
                        $memo = "加钟收入";
                        $ret = \app\admin\model\Steward::money($amount, $order->steward_id, $memo, $order->id);
                        // 结算加钟时间
                        \app\admin\model\OrderExtra::where(['order_id'=>$id,'paid'=>1])->update(['settletime'=>time()]);
                    }
                }
//                return $ret;
                // 修改管家状态为空闲中
                \app\admin\model\Steward::where(['id'=>$order->steward_id])->update(['service_status'=>1]);
            }


            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 删除
    public static function deleteOrder($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        if (!$id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }
        if (!$user_id) {
            return ['code' => 0, 'msg' => '用户信息不存在', 'data' => ''];
        }

        //判断订单是否存在
        $order = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->find();

        if (!$order) {
            return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
        }

        if ( $order['paid'] == 1 &&  in_array($order['status'],[0,1,2,3])) {
            return ['code' => 0, 'msg' => '订单已支付，请先取消订单再删除', 'data' => ''];
        }

        if ( $order['paid'] == 1 &&  $order['status'] == 4 ) {
            return ['code' => 0, 'msg' => '管家正在服务中订单不可删除', 'data' => ''];
        }

        try{

            $result = \app\admin\model\Order::where('id', $id)->where('user_id', $user_id)->update(['updatetime'=>time(),'deletetime'=>time()]);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }


    }



    // 获取管家位置
    public static function getStewardLocation($data){
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        $order = \app\admin\model\Order::where(['id'=>$id,'user_id'=>$user_id])->field('steward_id,status')->find();
        if(!$order ) return ['code'=>0,'msg'=>'订单信息不存在','data'=>''];

        if( $order['status']!= 2 && $order['status']!= 3 ) return ['code'=>0,'msg'=>'管家暂未出发，无法获取定位','data'=>''];

        $steward_id = $order['steward_id'];
        if( !$steward_id ) return ['code'=>0,'msg'=>'管家尚未更新位置信息','data'=>''];

        $location = \app\admin\model\Steward::where(['id'=>$order['steward_id']])->field('lng,lat')->find();
        if( isset($location['lng']) && $location['lng'] && isset($location['lat']) && $location['lat'] ){
            return ['code'=>1,'msg'=>'查询成功','data'=>['lng'=>$location['lng'],'lat'=>$location['lat']]];
        }
        return ['code'=>0,'msg'=>'卫星信号差','data'=>''];
    }

    // 获取学生照片
    public static function getStudentPhoto($data){
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;

        $order = \app\admin\model\Order::where(['id'=>$id,'user_id'=>$user_id])->field('student_photo,status')->find();
        if(!$order ) return ['code'=>0,'msg'=>'订单信息不存在','data'=>''];

        if( $order['status']!= 3 ) return ['code'=>0,'msg'=>'管家未到达学校,尚未更新学生照片','data'=>''];

        $student_photo = $order['student_photo'];
        if( $student_photo ) {
            return ['code'=>1,'msg'=>'查询成功','data'=>$student_photo];
        }
        return ['code'=>0,'msg'=>'尚未更新学生照片','data'=>''];
    }



    /**
     * 给图片加文字
     * $bg_path    背景图地址
     * $text		要添加的文字
     * $x           文字在背景图片上位置的左边距,单位：px （例：436）
     * $y           文字在背景图片上位置的上边距,单位：px （例：1009）
     * $font_size	字体大小,单位：px （例：20）
     * $echo_path   生成的新图片存放路径
     **/
    private static function imageAddText($bg_path, $text, $x, $y, $font_path, $font_size, $echo_path){
        $background = imagecreatefromstring(file_get_contents($bg_path));
        $font = $font_path; //字体在服务器上的绝对路径
        $black = imagecolorallocate($background, 0, 0, 0);//字体颜色黑色

        $str = mb_convert_encoding($text, "html-entities", "utf-8");

        imagefttext($background, $font_size, 0, $x, $y, $black, $font, $str);
        imagepng($background,$echo_path);
        imagedestroy($background);
        return $echo_path;
    }

    /**
     * base64编码字符串转换成图片并保存到本地
     * $base64_image_content    base64编码字符串
     * $path		路径
     **/
    private static function base64_image_content($base64_image_content,$path){
        $auth = Auth::instance();
        $user_id = $auth->id;

        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content,$result)){
            $type = $result[2];
            $new_file = $path."/sign/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file.$user_id.".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 透明png图片旋转270度
     * $sourcePath    图片路径
     * $savePath    保存路径
     * $angle		旋转角度
     **/
    private static function rotateImageGD($sourcePath, $savePath) {
        // 加载图片
        $sourceImage = imagecreatefrompng($sourcePath);

        // 获取图片尺寸
        $width = imagesx($sourceImage);
        $height = imagesy($sourceImage);

        // 创建一个新的图片，大小与原图交换
        $newImage = imagecreatetruecolor($height, $width);

        // 设置透明色
        imagealphablending($newImage, false);
        $transparent = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
        imagefill($newImage, 0, 0, $transparent);
        imagesavealpha($newImage, true);

        // 旋转图片270度
        for ($x = 0; $x < $width; $x++) {
            for ($y = 0; $y < $height; $y++) {
                // 获取原图像像素颜色
                $color = imagecolorat($sourceImage, $x, $y);
                // 将像素颜色设置到新图像的对应位置（交换宽高）
                imagesetpixel($newImage, $y, $width - $x - 1, $color);
            }
        }

        // 保存新图片
        imagepng($newImage, $savePath);

        // 释放内存
        imagedestroy($sourceImage);
        imagedestroy($newImage);
    }




    // 回调(测试用)
    public static function payResult($data)
    {
        //开启事务
        try{
            $order = \app\admin\model\Order::where('order_no', $data['out_trade_no'])->find();
            //判断是否已支付过
            if( $order->paid == 1 ){
                return false;
            }

            // //修改订单状态
//            if( $type == 'alipay' ){
//                $order->trade_no = $data['trade_no'];
//            }elseif( $type == 'wechat' ){
//                $order->trade_no = $data['transaction_id'];
//            }
            //修改订单状态
            $order->trade_no = $data['out_trade_no'];
            $order->paid = 1;
            $order->status = 0;
            $order->paidtime = time();
            $order_result = $order->save();

            if( $order_result  ){
                DB::commit();
                return true;
            }else{
                DB::rollback();
                return false;
            }
        }catch(\Exception $e){
            DB::rollback();
//            return $e->getMessage();
            return false;
        }
    }
}